<template>
  <div>
    <el-form :inline="true" :model="dataForm" @keyup.enter="getDataList()">
      <el-form-item>
        <el-input v-model="dataForm.teamName" placeholder="代表队名称" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="dataForm.realName" placeholder="选手姓名" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="dataForm.company" placeholder="单位" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-select v-model="dataForm.status" placeholder="状态">
          <el-option label="全部" value=""></el-option>
          <el-option label="审核中" value="0"></el-option>
          <el-option label="报名成功" value="1"></el-option>
          <el-option label="完赛" value="201"></el-option>
          <el-option label="已确认晋级" value="202"></el-option>
          <el-option label="已取消/弃权" value="3"></el-option>
          <el-option label="比赛中" value="4"></el-option>
          <el-option label="已获晋级赛资格" value="501"></el-option>
          <el-option label="放弃晋级" value="502"></el-option>
          <el-option label="晋级成功" value="6"></el-option>
          <el-option label="弃权" value="7"></el-option>
          <el-option label="驳回" value="8"></el-option>
          <el-option label="待确认" value="9"></el-option>
          <el-option label="报名已截止" value="10"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="地区" prop="province">
        <el-select style="width: 150px" placeholder="请选择" v-model="dataForm.province" @change="selectCity">
          <el-option value="" label="全国">全国</el-option>
          <el-option v-for="itemO in area.item" :key="itemO.code" :label="itemO.name" :value="itemO.code"> </el-option>
        </el-select>
        ~
        <el-select style="width: 150px" placeholder="请选择" v-model="dataForm.city">
          <el-option value="" label="全部">全部</el-option>
          <el-option v-for="itemO in areaCity.item" :key="itemO.code" :label="itemO.name" :value="itemO.code"> </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">{{ $t("query") }}</el-button>
      </el-form-item>
      <el-form-item>
        <el-button @click="exportHandle()">导出模板表</el-button>
      </el-form-item>
      <el-form-item>
        <el-button v-if="hasPermission('sp:spmatchitemrecord:genNo')" type="primary" :loading="btnLoading" @click="createCertificateNo()">生成证书编号</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" v-if="hasPermission('sp:spmatchitemrecord:genPic')" @click="certificateHandle()">生成证书图片</el-button>
      </el-form-item>
      <el-form-item>
        <el-tag size="big">{{ matchItem ? matchItem.match_name : "" }}</el-tag>
        <el-tag size="big" style="margin-left: 10px">{{ matchItem ? matchItem.item_name : "" }}</el-tag>
        <el-tag size="big" style="margin-left: 10px">{{ dataForm.groupNameFile ? dataForm.groupNameFile : "" }}</el-tag>
      </el-form-item>
    </el-form>
    <el-table v-loading="dataListLoading" :data="dataList" border @selection-change="dataListSelectionChangeHandle" @sort-change="dataListSortChangeHandle" style="width: 100%">
      <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
      <el-table-column prop="id" width="80" label="序号" sortable="custom" header-align="center" align="center"></el-table-column>
      <el-table-column prop="sort" width="120" label="抽签结果" header-align="center" align="center" v-if="dataForm.drawOpen == 1 && dataForm.isDraw == 1"></el-table-column>
      <el-table-column prop="teamName" width="250" label="代表队名称" header-align="center" align="center"></el-table-column>
      <el-table-column prop="company" width="250" label="选手单位" header-align="center" align="center"></el-table-column>
      <el-table-column prop="realName" width="200" label="选手" header-align="center" align="center">
        <template v-slot="scope">
          <el-button type="text" @click="detailHandle(scope.row.userId)">{{ scope.row.realName }}</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="ticket" width="150" label="选手编号" header-align="center" align="center"></el-table-column>
      <el-table-column prop="teacher" width="150" label="指导老师" header-align="center" align="center"></el-table-column>
      <el-table-column prop="score" v-if="scores[0]" width="100" :label="$t(scores[0])" header-align="center" align="center"></el-table-column>
      <el-table-column prop="score1" v-if="scores[1]" width="100" :label="$t(scores[1])" header-align="center" align="center"></el-table-column>
      <el-table-column prop="score2" v-if="scores[2]" width="100" :label="$t(scores[2])" header-align="center" align="center"></el-table-column>
      <el-table-column prop="ranks" width="100" label="名次" sortable="custom" header-align="center" align="center"></el-table-column>
      <el-table-column prop="grade" width="100" label="奖等" header-align="center" align="center"></el-table-column>
      <el-table-column prop="certificate" width="100" label="证书编号" header-align="center" align="center"></el-table-column>
      <el-table-column prop="status" width="120" label="状态" header-align="center" align="center">
        <template v-slot="scope">
          <el-tag>{{ statusTranslate(scope.row.status, scope.row) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('handle')" fixed="right" header-align="center" align="center" width="150">
        <template v-slot="scope">
          <el-button type="text" size="small" v-if="(scope.row.status === 1 || scope.row.status === 2) && scope.row.certificate_url && hasPermission('sp:spmatchitemrecord:infoCer')" @click="infoHandle(scope.row.certificate_url)">证书</el-button>
          <el-button type="text" size="small" v-if="(scope.row.status === 1 || scope.row.status === 2) && scope.row.certificate_url && hasPermission('sp:spmatchitemrecord:downCer')" @click="downloadHandle(scope.row.certificate_url, scope.row.realName + '-' + scope.row.certificate)">下载</el-button>
          <el-button type="text" size="small" v-if="(scope.row.status === 1 || scope.row.status === 2) && hasPermission('sp:spmatchitemrecord:uploadCer') && scope.row.certificate" @click="showUploadHandle(scope.row.matchItemTeamUserId)">上传证书</el-button>
          <el-button
            type="text"
            size="small"
            v-if="(scope.row.status === 1 || scope.row.status === 2 || (scope.row.status === 5 && scope.row.rejectReason == '放弃晋级')) && scope.row.certificate && hasPermission('sp:spmatchitemrecord:delCerNo')"
            @click="cancleCertificateNo(scope.row.matchItemTeamUserId)"
            >删除编号+图片</el-button
          >
          <el-button type="text" size="small" v-if="(scope.row.status === 1 || scope.row.status === 2) && scope.row.certificate_url && hasPermission('sp:spmatchitemrecord:delCer')" @click="updateHandle(scope.row.matchItemTeamUserId)">删除图片</el-button>
          <el-button type="text" size="small" v-if="(scope.row.status === 1 || scope.row.status === 2 || (scope.row.status === 5 && scope.row.rejectReason == '放弃晋级')) && hasPermission('sp:spmatchitemrecord:cancleScore')" @click="cancleScoreHandle(scope.row.matchItemTeamUserId)"
            >清除成绩</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination :current-page="page" :page-sizes="[10, 20, 50, 100]" :page-size="limit" :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="pageSizeChangeHandle" @current-change="pageCurrentChangeHandle"> </el-pagination>
    <upload v-if="uploadVisible3" ref="upload3" uploadurl="/sp/spmatchitemteam/importMatchScore" downloadurl="/sp/spmatchitemteam/exportMatchScoreError" @refreshDataList="getDataList"></upload>
    <detail v-if="detailVisible" ref="send" @refreshDataList="getDataList"></detail>
    <!--上传证书弹窗-->
    <el-dialog v-model="uploadVisible4" title="上传证书" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-upload class="text-center" drag :action="picUploadUrl" :show-file-list="false" :on-success="(response, file, fileList) => handleAvatarSuccess(response, file, fileList, 'pic4')">
        <img v-if="dataForm.zsPic" :src="dataForm.zsPic" class="avatar" width="100" height="150" />
        <el-icon v-if="!dataForm.zsPic" class="el-icon--upload"><upload-filled /></el-icon>
        <div v-if="!dataForm.zsPic" class="el-upload__text" v-html="$t('upload.text')"></div>
      </el-upload>
      <div style="text-align: center; margin-top: 20px">
        <el-button @click="uploadVisible4 = false">取 消</el-button>
        <el-button type="primary" @click="confirmUpload">确定上传</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import useView from "@/hooks/useView";
import { defineComponent, reactive, toRefs } from "vue";
import baseService from "@/service/baseService";
import app from "@/constants/app";
import qs from "qs";
import { getToken } from "@/utils/cache";
import Upload from "@/views/sp/score-upload.vue";
import Detail from "@/views/sp/spuser-detail.vue";
import {IObject} from "@/types/interface";
export default defineComponent({
  name: "RenRecordStudentGroup",
  components: {
    Upload,
    Detail
  },
  setup() {
    const state = reactive({
      uploadVisible3: false,
      uploadVisible4: false,
      picUploadUrl: "",
      getDataListURL: "/sp/spmatchitemteam/signRecordStudent",
      createdIsNeed: false,
      activatedIsNeed: false,
      getDataListIsPage: true,
      exportURL: "/sp/spmatchitemteam/exportStudent",
      deleteURL: "/sp/spmatchitemteam",
      deleteIsBatch: true,
      btnLoading: false,
      dataForm: {
        matchName: "",
        item: "",
        matchItemId: "",
        teamId: "",
        teamName: "",
        isRise: "",
        status: "",
        company: "",
        realName: "",
        groupId: "",
        groupNameFile: "",
        province: "",
        city: "",
        fileName: "",
        drawOpen: null,
        isDraw: null,
        zsPic: "",
        matchItemTeamUserId: "",
      },
      matchItem: {
        match_name: "",
        item_name: ""
      },
      scores: [],
      activeName: "first",
      area: { code: "0", item: [{ code: "0", name: "请选择" }] },
      areaCity: { code: "0", item: [{ code: "0", name: "请选择" }] },
      detailVisible: false
    });
    return { ...useView(state), ...toRefs(state) };
  },
  props: {
    itemType: String
  },
  watch: {},
  created() {
    this.areaList(this.area);
    this.picUploadUrl = `${app.api}/sys/oss/upload?token=${getToken()}`;
  },
  mounted() {
    //获取上个页面传来的参数
    this.dataForm.matchItemId = this.$route.query.matchItemId + "";
    this.dataForm.groupId = this.$route.query.id + "";
    this.dataForm.groupNameFile = this.$route.query.groupName + "";
    this.dataForm.drawOpen = this.$route.query.drawOpen + "";
    this.dataForm.isDraw = this.$route.query.isDraw + "";
    this.queryBymatchItemId(this.dataForm.matchItemId);
    this.query();
  },
  methods: {
    /**
     * 查询score配置
     * @param matchItemId
     */
    queryBymatchItemId(matchItemId: any) {
      baseService.post("/sp/spmatchitem/queryBymatchItemId", { id: matchItemId }).then((res) => {
        if (res.code !== 0) {
          return this.$message.error(res.msg);
        } else {
          this.matchItem = res.data;
          this.dataForm.fileName = this.matchItem.item_name + "(" + this.dataForm.groupNameFile + ")";
          this.scores = res.data.scores.split(",");
        }
      });
    },
    zhengshuHandle() {
      let ids: string[] = [];
      for (let i = 0; i < this.dataListSelections!.length; i++) {
        ids.push(this.dataListSelections![i].id);
      }
      window.location.href = `${app.api}/sp/spmatchitemteam/downloadFile?${qs.stringify({
        ...this.dataForm,
        token: getToken(),
        ids: ids.join(",")
      })}`;
    },
    uploadCertificate() {
      this.uploadVisible3 = true;
      this.$nextTick(() => {
        this.$refs.upload3.init();
      });
    },
    // 查看证书
    infoHandle(info: string) {
      window.open(info);
    },
    downloadHandle(url: string, name: string) {
      let a = document.createElement("a");
      let evt = document.createEvent("MouseEvents");
      a.download = "晋级列表";
      a.href = `${app.api}/sp/spticket/download?imageUrl=` + url + `&fileName=` + name + `.jpg`;
      evt.initEvent("click", true, true);
      a.dispatchEvent(evt);
      window.URL.revokeObjectURL(a.href);
    },
    /**
     * 根据SpMatchItemTeamUser.id删除证书
     * @param id
     */
    updateHandle(id: number) {
      this.$confirm("确认删除证书？", "删除证书", {
        confirmButtonText: this.$t("confirm"),
        cancelButtonText: this.$t("cancel"),
        type: "warning"
      }).then(() => {
        baseService.get("/sp/spmatchitemteam/delCertificate?id=" + id, {}).then((res) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.query();
          }
        });
      });
    },
    /**
     * 生成证书编号
     */
    createCertificateNo() {
      this.btnLoading = true;
      this.$confirm("确认生产证书编号？", "生成证书编号", {
        confirmButtonText: this.$t("confirm"),
        cancelButtonText: this.$t("cancel"),
        type: "warning"
      })
        .then(() => {
          // 确认
          baseService.get("/sp/spmatchitemteam/createCertificateNo", this.dataForm).then((res) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg);
            } else {
              this.$confirm("证书编号需要等待一段时间,请勿重复点击！", "提示", {
                confirmButtonText: this.$t("confirm"),
                cancelButtonText: this.$t("cancel"),
                type: "warning"
              }).then(() => {
                this.query();
              });
            }
            this.btnLoading = false;
          });
        })
        .catch(() => {
          // 取消
          this.btnLoading = false;
        });
    },
    /**
     * 删除证书编号
     */
    cancleCertificateNo(id: number) {
      this.$confirm("确认删除编号+图片？", "删除编号+图片", {
        confirmButtonText: this.$t("confirm"),
        cancelButtonText: this.$t("cancel"),
        type: "warning"
      }).then(() => {
        baseService.get("/sp/spmatchitemteam/cancelCertificateNo?id=" + id, {}).then((res) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.query();
          }
        });
      });
    },
    /**
     * 生成证书图片
     * @param id
     */
    certificateHandle(id?: string) {
      this.$confirm("确认生成证书？", "生成证书", {
        confirmButtonText: this.$t("confirm"),
        cancelButtonText: this.$t("cancel"),
        type: "warning"
      }).then(() => {
        baseService.get("/sp/spmatchitemteam/certificate", this.dataForm).then((res) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.query();
          }
        });
      });
    },
    // 获取省份
    areaList(target: any) {
      baseService.get("/front/fast/sys/areaDict/list?pid=" + target.code).then((e: any) => {
        target.item = e.data;
      });
    },
    // 选择城市
    selectCity() {
      if (this.dataForm.province) {
        this.areaCity.code = this.dataForm.province;
        this.areaList(this.areaCity);
      } else {
        this.dataForm.city = "";
        this.areaCity.item = [];
      }
    },
    detailHandle(id?: string) {
      this.detailVisible = true;
      baseService.get("/sp/spuser/" + id).then((e: any) => {
        this.$nextTick(() => {
          if (e.data) {
            e.data.sex = e.data.sex == 0 ? "女" : "男";
          }
          this.$refs.send.dataForm.row = e.data;
          this.$refs.send.init();
        });
      });
    },
    /**
     * 清除成绩
     * @param id  matchItemTeamId
     */
    cancleScoreHandle(matchItemTeamUserId?: string) {
      this.$confirm("确认清除成绩？", "清除成绩", {
        confirmButtonText: this.$t("confirm"),
        cancelButtonText: this.$t("cancel"),
        type: "warning"
      }).then(() => {
        baseService.post("/sp/spmatchitemteam/cancleScoreStudent", { id: matchItemTeamUserId }).then((res) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg);
          } else {
            this.query();
          }
        });
      });
    },
    // 上传证书弹窗
    showUploadHandle(id: any) {
      this.uploadVisible4 = true;
      this.dataForm.zsPic = "";
      this.dataForm.matchItemTeamUserId = id;
    },
    // 确定上传
    confirmUpload() {
      baseService.post("/sp/spmatchitemteamuser/updCertificate", { id: this.dataForm.matchItemTeamUserId, certificateUrl: this.dataForm.zsPic, type: "student" }).then((e: any) => {
        this.uploadVisible4 = false;
        this.query();
      });
    },
    // 上传证书后保存
    handleAvatarSuccess(res: IObject, file: IObject, fileList: IObject, type: string) {
      this.dataForm.zsPic = res.data.src;
      this.$message.success("上传成功");
    },



  }
});
</script>
